package com.zhiqian.community.quartz;

import com.zhiqian.community.entity.DiscussPost;
import com.zhiqian.community.entity.Event;
import com.zhiqian.community.event.EventProducer;
import com.zhiqian.community.service.DiscussPostService;
import com.zhiqian.community.service.LikeService;
import com.zhiqian.community.util.CommunityConstant;
import com.zhiqian.community.util.RedisKeyUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/**
 * 刷新帖子分数定时任务
 */
public class PostScoreRefreshJob implements Job, CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(PostScoreRefreshJob.class);
    //社区时间
    private static final Date epoch;
    static{
        try {
            epoch = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2014-04-01 00:00:00");
        } catch (ParseException e) {
            throw new RuntimeException("初始化社区时间失败",e);
        }
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String variationPostKey = RedisKeyUtil.getVariationPostKey();
        Set<Integer> set = redisTemplate.opsForSet().members(variationPostKey);
        if (set.size()==0){
            logger.info("[任务取消] 没有需要更新的帖子");
            return;
        }
        logger.info("[任务开始] 正在更新帖子分数："+set.size());
        set.forEach(postId -> {
            refresh(postId);
        });
        redisTemplate.delete(variationPostKey);
        logger.info("[任务结束] 帖子分数更新完毕");
    }

    /**
     * 计算并更新帖子分数
     * @param postId
     */
    private void refresh(Integer postId) {
        DiscussPost post = discussPostService.selectDiscussPostById(postId);
        if (post ==null){
            logger.error("[定时任务] 该帖子不存在，id="+postId);
            return;
        }
        //是否加精
        boolean quintessence = post.getStatus()==DISCUSSPOST_STATUS_QUINTESSENCE;
        Long likeCount = likeService.queryEntityLikeCount(ENTITY_TYPE_POST, postId);
        Integer commentCount = post.getCommentCount();
        double w = (quintessence?75:0) + commentCount*10 +likeCount*2;
        double score = Math.log10(Math.max(w,1))+ (post.getCreateTime().getTime() -epoch.getTime())/(1000*3600*24);
        discussPostService.updatePostScore(postId,score);
        Event event=createUpdatePostEvent(postId);
        eventProducer.fireEvent(event);
    }

    private Event createUpdatePostEvent(Integer postId) {
        Event event = new Event();
        event.setTopic(TOPIC_PUBLISH);
        event.setEntityType(ENTITY_TYPE_POST);
        event.setEntityId(postId);
        return event;
    }
}
